﻿using System.Collections.Generic;
using System.Configuration;

namespace AsicMonitor
{
    class AppConfig
    {
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

        public static List<string> GetAppConfigArray(string strKey)
        {
            string countStr = GetAppConfig($"{strKey}_count");
            List<string> ret = new List<string>();

            if (int.TryParse(countStr, out int count))
            {
                for(int i = 0; i < count; i++)
                {
                    string key = $"{strKey}_{i}";
                    string item = GetAppConfig(key);
                    if(item != null && item != "")
                    {
                        ret.Add(item);
                    }
                }
            }

            return ret;
        }

        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
